import java.util.ArrayList;
import java.util.List;

/**
 * @author SaoE
 * @date 2025/3/22 14:39
 */
public class _54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        int left = 0;
        int right = matrix[0].length - 1;
        int top = 0;
        int bottom = matrix.length - 1;
        while (left <= right && top <= bottom){
            for (int i = left; i <= right; i++){
                res.add(matrix[top][i]);
            }
            for (int i = top + 1; i <= bottom; i++){
                res.add(matrix[i][right]);
            }
            for (int i = right - 1; i >= left && top != bottom; i--){
                res.add(matrix[bottom][i]);
            }
            for (int i = bottom - 1; i > top && left != right; i--){
                res.add(matrix[i][left]);
            }
            left++;
            right--;
            top++;
            bottom--;
        }

        return res;
    }
}
